#-*- coding:utf-8 -*-

# The MIT License (MIT)
# 
# Copyright (c)  2014  Li Lin  <jzqlin@gmail.com>
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

"""UAFramework implements a basic system of the user register\login\authenticate
features for users management.

The framework is based on SQLAlchemy. Developers need to setup a basic database environment 
for user's basic information's storage. Developers can design other database for 
the user's external information.
"""

__all__ = ['database', 'authenticate', 'register']

# The framework version
__version__ = '0.0.1'

# tools for setup user management's basic database environment 


from database.splitter import TableSplitter, DatabaseSplitter
from database.user_basic import UAUserBasic
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base   
import random 


        
def setup_user_basic_mysql(dbhost, dbport, dbuser, dbpwd):
    """Call this method when you first time use of this framework. This method create all 
    the databases and tables needed for the framework, and should be called only once. 
    """
    
    # split databases
    database_urls = []
    for i in range(0, 100):
        db_url = "mysql://%s:%s@%s:%s/d_ua_user_basic_%d" % (dbuser, dbpwd, dbhost, dbport, i)
        database_urls.append(db_url) 

    # create databases
    engine = create_engine("mysql://%s:%s@%s:%s" % (dbuser, dbpwd, dbhost, dbport))
    conn = engine.connect()
    conn.execute("commit")
    
    for i in range(0, 100):
        conn.execute("create database if not exists d_ua_user_basic_%d " % i)
        print("schema d_ua_user_basic_%d created" % i)

    ua_user_basic_databases = DatabaseSplitter(database_urls)
     
    # create tables 
    table_names = []
    table_mapped_class_names = []
    for i in range(0, 100):
        table_names.append("t_user_basic_%d" % i)
        table_mapped_class_names.append("UAUserBasic%d" % i)
        
    ua_user_basic_classes = TableSplitter(table_names, UAUserBasic, table_mapped_class_names)

    for i in range(0, 100):
        ua_user_basic_classes.sqlalchemy_base.metadata.create_all(ua_user_basic_databases.engines[i])
        print("tables in database ua_user_basic_databases[%d] created" % i)
    
    conn.close()
    
    return (ua_user_basic_databases, ua_user_basic_classes)
    
    
                
def prepare_user_basic_mysql(dbhost, dbport, dbuser, dbpwd): 
    """Prepare the objects needed to operate databases. 
    """       
    # split databases
    database_urls = []
    for i in range(0, 100):
        db_url = "mysql://%s:%s@%s:%s/d_ua_user_basic_%d" % (dbuser, dbpwd, dbhost, dbport, i)
        database_urls.append(db_url) 
        
    ua_user_basic_databases = DatabaseSplitter(database_urls)
    
    # split tables    
    table_names = []
    table_mapped_class_names = []
    for i in range(0, 100):
        table_names.append("t_user_basic_%d" % i)
        table_mapped_class_names.append("UAUserBasic%d" % i)
        
    ua_user_basic_classes = TableSplitter(table_names, UAUserBasic, table_mapped_class_names)        
        
    return (ua_user_basic_databases, ua_user_basic_classes)        

        
        
def gen_token(token_len=15):
    """generate random string token with size of token_len"""
     
    seeds = '1234567890ABCDEFGHIJKLMNOPJRSTUVSWXYZ'
    seeds_len = len(seeds)
        
    newToken = ''      
          
    for i in range(token_len):      
        idx = random.randint(0, seeds_len - 1)        
        newToken = newToken + seeds[idx]        
                    
    return newToken
 






